const uniID = require('uni-id-common');
const db = uniCloud.database();

exports.main = async (event, context) => {
    const uniIDIns = uniID.createInstance({ context });

    let body = event;
    if (event.body != undefined) {
        body = JSON.parse(event.body)
    }

    try {
        // 1. 身份验证
        const { uid } = await uniIDIns.checkToken(body.uniIdToken);
        if (!uid) {
            return { success: false, code: 403, message: "用户身份验证失败" };
        }

        const { uid: consultantId } = await uniIDIns.checkToken(body.consultantUniIdToken);
        if (!consultantId) {
            return { success: false, code: 403, message: "咨询师身份验证失败" };
        }

        // 2. 参数提取
        let { day, appointedSlot } = body;

        // 3. 参数存在性检查
        if (!day || !appointedSlot) {
            return {
                success: false,
                code: 400,
                message: "缺少必要的参数"
            };
        }

        // 4. 日期格式校验
        const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
        if (!dateRegex.test(day)) {
            return {
                success: false,
                code: 400,
                message: "日期格式不正确，应为 YYYY-MM-DD 格式"
            };
        }

        const dateObj = new Date(day);
        if (isNaN(dateObj.getTime())) {
            return {
                success: false,
                code: 400,
                message: "提供的日期无效"
            };
        }

        // 5. 时间段格式校验
        const timeSlotRegex = /^([01]?[0-9]|2[0-3]):00-([01]?[0-9]|2[0-3]):50$/;
        if (!timeSlotRegex.test(appointedSlot)) {
            return {
                success: false,
                code: 400,
                message: "时间段格式不正确",
                details: {
                    appointedSlot,
                    requiredFormat: "必须为整点开始、50分钟结束的区间，例如: 09:00-09:50"
                }
            };
        }

        // 验证时间差是否为50分钟
        const [startTime, endTime] = appointedSlot.split('-');
        const [startHour, startMinute] = startTime.split(':').map(Number);
        const [endHour, endMinute] = endTime.split(':').map(Number);
        const startTotal = startHour * 60 + startMinute;
        const endTotal = endHour * 60 + endMinute;

        if (endTotal - startTotal !== 50) {
            return {
                success: false,
                code: 400,
                message: "时间段长度不是50分钟"
            };
        }

        // 6. 检查是否有未完成的预约
        const collection = db.collection("appoint_schedule");
        const unfinishedAppointmentsQuery = await collection.where({ uid }).get();

        if (unfinishedAppointmentsQuery.data.length > 0) {
            return {
                success: false,
                code: 409,
                message: "您有未完成的预约，请先完成当前预约"
            };
        }

        // 7. 检查该时段是否已被预约
        const reservationQuery = await collection.where({ consultant: consultantId, day, appointedSlot }).get();
        if (reservationQuery.data.length > 0) {
            return {
                success: false,
                code: 409,
                message: "该时间段已被预约"
            };
        }

        // 8. 插入新的预约记录
        const res = await collection.add({
            uid,
            consultant: consultantId,
            day,
            appointedSlot,
            create_date: new Date().toISOString(),
            hasSubscribed: false,
            hasSent: false
        });

        return {
            success: true,
            code: 200,
            message: "预约成功",
            appointmentId: res.id
        };
    } catch (error) {
        console.error("数据库操作失败:", error);
        return {
            success: false,
            code: 500,
            message: "数据库操作失败",
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        };
    }
};
